<template>
	<view>
		<view v-if="authorized">
			<view class="head-container">
				<image :src="avatar" mode="aspectFill" class="img-avatar"></image>
				<view class="user-info-container">
					<view class="nick-type-container">
						<text class="nick-badge">{{nick +"-" +"["+uTypes[type] +"]"}}</text>
						<image :src="badges[type]" mode="widthFix" class="img-badge"></image>
					</view>
					<text class="user-email">{{user +":" +email}}</text>
				</view>
			</view>
			<text class="iconfont icon-zhuxiao" @click="clickLogout"></text>
<!--      发布的博客-->
			<view class="data-container">
				<view class="data-title" @click="clickSwitch(0)">
					<text class="data-title-name">我发布的{{myCount}}篇文章</text>
					<text :class="status[0].visible ? 'iconfont icon-xiangxia ic-arrow ':'iconfont icon-xiangshang ic-arrow'"></text>
				</view>
				<scroll-view v-if="status[0].visible" scroll-x class="scroll" scroll-with-animation="true" @scrolltolower="getMyBlogs">
					<view v-for="(blog,index) in myBlogs" :key="'m_' +blog.id" class="scroll-item" @click="clickGoBlog(blog.id)">
						<image :src="blog.picture" mode="aspectFill"></image>
						<text>{{blog.title}}</text>
					</view>
				</scroll-view>
			</view>


      <!-- 点赞过的博客-->
      <view class="data-container">
        <view class="data-title" @click="clickSwitch(3)">
          <text class="data-title-name">我点赞过的{{goodCount}}篇文章</text>
          <text :class="status[3].visible ? 'iconfont icon-xiangxia ic-arrow ':'iconfont icon-xiangshang ic-arrow'"></text>
        </view>
        <scroll-view v-if="status[3].visible" scroll-x class="scroll" enable-flex scroll-with-animation="true" @scrolltolower="getBlogs">
          <view v-for="(blog,index) in goodBlogs" @click="clickGoBlog(blog.id)" :key="'g_'+blog.id"
                class="scroll-item">
            <image :src="blog.picture" mode="aspectFill"></image>
            <text>{{blog.title}}</text>
          </view>
        </scroll-view>
      </view>


      <!-- 类别数据管理 -->
      <view class="data-container">
				<view class="data-title" @click="clickSwitch(1)">
					<text class="data-title-name">我管理的6条类别数据</text>
					<text :class="status[1].visible ? 'iconfont icon-xiangxia ic-arrow ':'iconfont icon-xiangshang ic-arrow'"></text>
				</view>
				<view v-if="status[1].visible" class="data-list">
					<view class="data-item" v-for="(c,index) in categories" :key="c.id">
						<text class="data-item-name" @click="clickToUpdate(c.id,c.name)">{{c.name}}</text>
						<text :class="c.count==0?'data-item-btn':'data-item-count'" @click="c.count==0?clickDelete(c.id,c.name):''">{{c.count==0?'X':c.count}}</text>
					</view>
          <view class="data-item">
            <text class="iconfont icon-tianjia ic-add" @click="clickAdd"></text>
          </view>
				</view>
			</view>
      <view class="data-container">
        <!-- 标签数据管理 -->
        <view class="data-title" @click="clickSwitch(2)">
          <text class="data-title-name">管理{{tags.length}}个标签数据</text>
          <text :class="status[2].visible ? 'iconfont icon-xiangxia ic-arrow ':'iconfont icon-xiangshang ic-arrow'"></text>
        </view>
        <view v-if="status[2].visible" class="data-list">
          <view class="data-item" v-for="(c,index) in tags" :key="c.id">
            <text class="data-item-name" @click="clickToUpdate(c.id,c.name)">{{c.name}}</text>
            <text :class="c.count==0?'data-item-btn':'data-item-count'"
                  @click="c.count==0? clickDelete(c.id,c.name):''">{{c.count==0 ? 'X':c.count}}</text>
          </view>
          <view class="data-item">
            <text class="iconfont icon-tianjia ic-add" @click="clickAdd"></text>
          </view>
        </view>
      </view>
	  


	<view class="data-container"></view>
      <dialog-shell ref="add_shell" title="添加新类别" @confirm="confirmAdd">
        <input type="text" placeholder="请输入类别名称" @input="inputGetName" focus
               style="margin:20rpx;padding-left: 10rpx;" />
      </dialog-shell>
      <dialog-shell ref="updateShell" title="更新类别" @confirm="confirmUpdate">
        <input type="text" :value="oldValue" placeholder="请输入类别名称" />
      </dialog-shell>
		</view>
		<login-dialog ref="login" @after="afterLogin"></login-dialog>
	</view>
</template>

<script>
	let app = getApp()
	let page = 0
  let newName = ''
  let updateId = ''
  let ids = []
	export default {
		data() {
			return {
				authorized: app.globalData.token.length > 0,
				avatar: this.$params.host + app.globalData.avatar,
				nick: app.globalData.nickName,
				type: app.globalData.type,
				uTypes: ["管理员", "认证博主", "普通会员"],
				badges: ["../../static/icons/badge0.png", "../../static/icons/badge1.png",
					"../../static/icons/badge2.png"
				],
				user: app.globalData.userName,
				email: app.globalData.email,
				status:[
					{visible:false},
					{visible:false},
					{visible:false},
					{visible:false},
				],
				myBlogs:[],
				myCount:-1,
        goodBlogs: [],
        goodCount: -1,
				categories:[],
        tags: [],
        oldValue: '',
			}
		},
		onLoad() {
			this.$noti.add(this.$params.noti_login_status, this.afterLogin, this)
		},
		onShow() {
		    if(!this.authorized){
				return
			}	
			this.loadData()
		},
		onUnload() {
			this.$noti.remove(this.$params.noti_login_status, this)
		},
		mounted() {
			this.authorized = app.globalData.token.length > 0
			if (!this.authorized) {
				this.$refs.login.show()
			}
		},
		methods: {
			clickGoBlog(id){
				uni.navigateTo({
					url:'../blog/blog?id=' + id,
					success:res=>{},
					fail:()=>{},
					complete:()=>{}	
				})
			},
			loadData(){
				this.myBlogs =[]
				this.myCount =-1
        this.goodBlogs = []
        this.goodCount = -1
				page =0
        this.getLocalGood()
        this.getBlogs()
				this.getMyBlogs()
				this.getCategories()
        this.getTags()

			},
			getMyBlogs(){
				if(this.myCount >=0 &&this.myBlogs.length ==this.myCount){
					return
				}
				let header ={
					"content-type":"application/json;charset=UTF-8",
					"page":page++,
					"size":2
				}
				let url =this.$params.host + this.$params.action_my_blogs +app.globalData.uid
				this.$request.getWithHeader(url,header,res =>{
					res.data.forEach(blog =>{
						if(!blog.picture.startsWith('http')){
							blog.picture =this.$params.host +blog.picture
						}
					})
					this.myBlogs =this.myBlogs.concat(res.data)
					this.myCount =parseInt(res.message)
					this.status[0].visible = this.myCount >0
				},()=>{})
				
			},
			clickSwitch(index){
				let now =this.status[index].visible
				this.status[index].visible =!now
			},
			afterLogin() {
				if(this.authorized){
					return
				}
				this.authorized = app.globalData.token.length > 0
				this.nick = app.globalData.nickName
				this.type = app.globalData.type
				this.user = app.globalData.userName
				this.email = app.globalData.email
				this.avatar = this.$params.host + app.globalData.avatar
				this.loadData()
			},
			clickLogout() {
				let url = this.$params.host + this.$params.action_logout
				let data = {
					token: app.globalData.token
				}
				this.$request.postParam(url, data, res => {
					uni.showToast({
						title: res.message,
						icon: 'none'
					});
					if (res.success) {
						this.authorized = false
						app.globalData.avatar = "/static/icons/default_user.png"
						app.globalData.type = -1
						app.globalData.nickName = ""
						app.globalData.userName = ""
						app.globalData.token = ""
						app.globalData.email = ""
						this.myBlogs =[]
						this.myCount =-1
						page =0
						this.$refs.login.show()
					}

				}, () => {})
			},
			getCategories(){
				//todo:首先检查用户身份,只有管理员才可以请求类别数据
				this.categories = []
				let url =this.$params.host +this.$params.action_categories
				this.$request.get(url,res =>{
					url =this.$params.host +this.$params.action_category_count
				  res.data.forEach(async (c) =>{
					  // let categories =[]
					  let r = await this.$request.requestAsync(url + c.id)
					  if(r.data.success){
						  let category = {
							  id:c.id,
							  name:c.name,
							  count:r.data.data
						  }
						  this.categories.push(category)
					  }
				  })
				  
				},()=>{})
			},
      //获取标签
      getTags() {
        this.tags = []
        let url = this.$params.host + this.$params.action_tags
        this.$request.get(url, res => {
          url = this.$params.host + this.$params.action_tags_count
          let i = 0
          res.data.forEach(async (c) => {
            let res = await this.$request.requestAsync(url + c.id)
            if (res.data.success) {
              let tag = {
                id: c.id,
                name: c.name,
                count: res.data.data
              }
              this.tags.push(tag)
            }
          })
          // console.log(res);
        },()=>{})
      },
      // 下面三个方法添加新类别数据
      clickAdd() {
        this.$refs.add_shell.show()
      },
      inputGetName(e) {
        newName = e.detail.value
      },
      confirmAdd() {
        //检查数据合法性
        if (!this.$util.checkLength(newName, 2, "类别名称")) {
          return
        }
        let url = this.$params.host + this.$params.action_category_add
        let data = {
          token: app.globalData.token,
          name: newName
        }
        this.$request.requestAsync(url, data, 'POST').then(res => {
          if (res.data.success) {
            let item = {
              id: res.data.data.id,
              name: res.data.data.name,
              count: 0
            }
            this.categories.push(item)
            newName = ""
          } else {
            uni.showToast({
              title: res.data.message,
              icon: 'none'
            });
          }
        }).catch(err => {
          newName = ""
          console.log(err)
        })
      },
      clickToUpdate(id, name) {
        this.oldValue = name
        newName = name
        updateId = id
        this.$refs.updateShell.show()
      },
      confirmUpdate() {
        // if (!this.$util.checkLength(newName, 2, '类别名称')) {
        //   return
        // }
        let url = this.$params.host + this.$params.action_category_update + updateId
        let data = {
          token: app.globalData.token,
          name: newName
        }
        this.$request.requestAsync(url, data, 'PUT').then(res => {
          if (res.data.success) {
            this.categories.forEach(c => {
              // c.name = res
              if (c.id == res.data.data.id) {
                c.name = res.data.data.name
              }
            })
          } else {
            uni.showToast({
              title: res.data.message,
              icon: 'none'
            });
          }
        }).catch(err => {
          console.log(err);
        })
      },

      clickDelete(id, name) {
        let url = this.$params.host + this.$params.action_category_delete + id
        let data = {
          token: app.globalData.token
        }
        uni.showModal({
          title: '删除确认',
          content: '确认要删除'+name+'吗?',
          showCancel: true,
          cancelText: '算了',
          confirmText: '删除',
          success: res => {
            if (res.confirm) {
              this.$request.del(url, data, res => {
                console.log(res);
                if (res.success) {
                  this.categories = this.categories.filter(c => c.id != id)
                } else {
                  uni.showToast({
                    title: res.message,
                    icon: 'none'
                  });
                }
              })
            }
          },
          fail: () => {},
          complete: () => {}
        });
      },
      getLocalGood() {
        let local = uni.getStorageSync(this.$params.key_good_ids)
        if (local) {
          ids = local
        }
        this.goodCount = ids.length
      },
      getBlogs() { //获取点赞博客
        if (this.goodCount >= 0 && this.goodBlogs.length == this.goodCount) {
          return
        }
        let url = this.$params.host + this.$params.action_blog
        this.$request.get(url, res => {
          console.log(res)
          res.data.forEach(blog =>{
            if(!blog.picture.startsWith('http')){
              blog.picture =this.$params.host +blog.picture
            }
          })
          this.goodBlogs =this.goodBlogs.concat(res.data)
          // this.goodCount =parseInt(res.message)
          // this.status[3].visible = this.goodCount >0
        },()=>{})

      },

		}
	}
</script>

<style>
	@import url("profile.css");
</style>